﻿<%@ WebHandler Language="C#" Class="AjaxMergeFiles" %>

using System;
using System.IO;
using System.Linq;
using System.Web;
using Business.Common;
using Business.Model.WebUploader;

public class AjaxMergeFiles : IHttpHandler
{
    //合并文件
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        var uploadDirectory = context.Request["uploadDirectory"];
        var guid = context.Request["guid"];
        var fileExt = context.Request["fileExt"];
        var root = context.Server.MapPath(string.Concat("~/", uploadDirectory, "/"));
        var sourcePath = Path.Combine(root, guid + "/");//源数据文件夹
        var targetPath = Path.Combine(root, Guid.NewGuid() + fileExt);//合并后的文件
        var dicInfo = new DirectoryInfo(sourcePath);
        if (Directory.Exists(Path.GetDirectoryName(sourcePath)))
        {
            var files = dicInfo.GetFiles();
            foreach (var file in files.OrderBy(f => int.Parse(f.Name)))
            {
                using (var addFile = new FileStream(targetPath, FileMode.Append, FileAccess.Write))
                {
                    using (var addWriter = new BinaryWriter(addFile))
                    {
                        //获得上传的分片数据流
                        using (var stream = file.Open(FileMode.Open))
                        {
                            using (var tempReader = new BinaryReader(stream))
                            {
                                //将上传的分片追加到临时文件末尾
                                addWriter.Write(tempReader.ReadBytes((int)stream.Length));
                            }
                        }
                    }
                }
            }
            DeleteFolder(sourcePath);
            var result = new ChunkedResult
            {
                chunked = true,
                hasError = false,
                savePath = HttpUtility.UrlEncode(targetPath)
            };
            context.Response.Write(result.T2Json());
        }
        else
        {
            var result = new ChunkedResult { hasError = true };
            context.Response.Write(result.T2Json());
        }
    }

    /// <summary>
    /// 删除文件夹及其内容
    /// </summary>
    /// <param name="strPath"></param>
    private static void DeleteFolder(string strPath)
    {
        //删除这个目录下的所有子目录
        Directory.GetDirectories(strPath).ToList().ForEach(file => Directory.Delete(file, true));
        //删除这个目录下的所有文件
        Directory.GetFiles(strPath).ToList().ForEach(file => File.Delete(file));
        Directory.Delete(strPath, true);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}